package com.oascarmovie;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

import com.oascarmovie.helper.HttpSender;
import com.oascarmovie.model.CatalogModel;

public class LoadCatalogThread extends Thread {

  private Handler uiRenderHandler;

  public LoadCatalogThread(Handler uiRenderHandler) {
    this.uiRenderHandler = uiRenderHandler;
  }

  @Override
  public void run() {
    requestCatalog();
    //http://localhost/OscarMovie/getMovieListAction.action?calendarId=0&awardId=0&categoryId=0&countryId=0&personId=0&paging.currentPage=1&type=0
  }

  private void requestCatalog() {
    Map<String, List<CatalogModel>> allCatalogMap = new HashMap<String, List<CatalogModel>>();
    try {
      
      allCatalogMap.put(Constants.CATALOG_CALENDAR, getCatalogList(Constants.CATALOG_CALENDAR));
      allCatalogMap.put(Constants.CATALOG_AWARD, getCatalogList(Constants.CATALOG_AWARD));
      allCatalogMap.put(Constants.CATALOG_CATEGORY, getCatalogList(Constants.CATALOG_CATEGORY));
      allCatalogMap.put(Constants.CATALOG_COUNTRY, getCatalogList(Constants.CATALOG_COUNTRY));
      
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Message message = Message.obtain(uiRenderHandler);
    message.what = Constants.MESSAGE_WHAT_REQUEST_CATALOG;
    message.obj = allCatalogMap;
    uiRenderHandler.sendMessage(message);
  }
  
  private List<CatalogModel> getCatalogList(String catalog) throws JSONException {
    JSONObject jsonObject = HttpSender
        .send(Constants.HTTP_HOST, Constants.HTTP_HOST + "/OscarMovie/masterDataAction!" + catalog);
    List<CatalogModel> catalogList = new ArrayList<CatalogModel>();
    JSONArray jsonArray = jsonObject.getJSONArray(jsonObject.keys().next().toString());
    for(int i = 0; i < jsonArray.length(); i++) {
      CatalogModel award = CatalogModel.build(jsonArray.getJSONObject(i));
      catalogList.add(award);
    }
    
    return catalogList;
  }

}
